package com.duapk.web.util;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * http工具类
 * 
 * @author yangfeng
 * 
 */
public class HttpUtils {

	private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);

	private static final String HTTP_GET = "GET";

	private static final String HTTP_POST = "POST";

	public static final String UTF_HTTP_ENCODING = "UTF-8";
	
	public static final String HTML_DEFALUT_ENCODING = "ISO-8859-1";

	/**
	 * 通过HTTP GET 发送参数
	 * 
	 * @param httpUrl
	 * @param parameter
	 * @param httpMethod
	 */
	public static String sendGet(String httpUrl, Map<String, String> parameter,
			String httpMethod) {
		if (parameter == null || httpUrl == null) {
			return null;
		}

		StringBuilder sb = new StringBuilder();
		Iterator<Map.Entry<String, String>> iterator = parameter.entrySet()
				.iterator();
		while (iterator.hasNext()) {
			if (sb.length() > 0) {
				sb.append('&');
			}
			Entry<String, String> entry = iterator.next();
			String key = entry.getKey();
			String value = entry.getValue();
			sb.append(key).append('=').append(value);
		}
		String urlStr = null;
		if (httpUrl.lastIndexOf('?') != -1) {
			urlStr = httpUrl + '&' + sb.toString();
		} else {
			urlStr = httpUrl + '?' + sb.toString();
		}

		HttpURLConnection httpCon = null;
		String responseBody = null;
		try {
			URL url = new URL(urlStr);
			httpCon = (HttpURLConnection) url.openConnection();
			httpCon.setDoOutput(true);
			httpCon.setRequestMethod(HTTP_GET);

			// 开始读取返回的内容
			InputStream in = httpCon.getInputStream();
			byte[] readByte = new byte[1024];
			// 读取返回的内容
			int readCount = in.read(readByte, 0, 1024);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			while (readCount != -1) {
				baos.write(readByte, 0, readCount);
				readCount = in.read(readByte, 0, 1024);
			}
			responseBody = new String(baos.toByteArray(), UTF_HTTP_ENCODING);
			baos.close();
		} catch (Exception e) {
			logger.error("Http Send POST Failed! url=" + httpUrl, e);
		} finally {
			if (httpCon != null)
				httpCon.disconnect();
		}
		return responseBody;
	}

	/**
	 * 使用HTTP POST 发送文本
	 * 
	 * @param httpUrl
	 *            发送的地址
	 * @param postBody
	 *            发送的内容
	 * @return 返回HTTP SERVER的处理结果,如果返回null,发送失败
	 */
	public static String sentPost(String httpUrl, String postBody) {
		return sentPost(httpUrl, postBody, UTF_HTTP_ENCODING);
	}
	
	public static void main(String[] args){
		
		String postBody = "{\"Body\":{\"SMSCfgVersion\":\"1\",\"IMEI\":\"356693036674135\",\"IMSI\":\"460000230960584\",\"SMSC\":\"13800755500\"},\"CommandID\":1025,\"Version\":\"2.0\",\"MsgID\":50,\"RetCode\":0,\"NodeType\":0};";
//		String postBody = "";
		System.out.println(sentPost("http://127.0.0.1:8890/smspay",postBody,"utf-8"));
	}

	/**
	 * 使用HTTP POST 发送文本
	 * 
	 * @param httpUrl
	 *            发送的地址
	 * @param postBody
	 *            发送的内容
	 * @param encoding
	 *            发送的内容的编码
	 * @return 返回HTTP SERVER的处理结果,如果返回null,发送失败
	 */
	public static String sentPost(String httpUrl, String postBody,
			String encoding) {
		HttpURLConnection httpCon = null;
		String responseBody = null;
		try {
			URL url = new URL(httpUrl);
			httpCon = (HttpURLConnection) url.openConnection();
			httpCon.setDoOutput(true);
			httpCon.setConnectTimeout(5000);
			httpCon.setRequestMethod(HTTP_POST);
			OutputStream output = httpCon.getOutputStream();
			output.write(postBody.getBytes(encoding));
			output.flush();
			output.close();

			if (logger.isDebugEnabled()) {
				int code = httpCon.getResponseCode();
				String result = httpCon.getResponseMessage();
				logger.debug("Http URL = " + httpUrl);
				logger.debug("code=" + code);
				logger.debug("ResponseMsg=" + result);
			}

			// 开始读取返回的内容
			InputStream in = httpCon.getInputStream();
			int size = in.available();
			byte[] readByte = new byte[size];
			// 读取返回的内容
			int readCount = in.read(readByte, 0, size);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			while (readCount != -1) {
				baos.write(readByte, 0, readCount);
				readCount = in.read(readByte, 0, size);
			}
			responseBody = new String(baos.toByteArray(), encoding);
			baos.close();
		} catch (Exception e) {
			logger.error("Http Send POST Failed! url=" + httpUrl, e);
		} finally {
			if (httpCon != null)
				httpCon.disconnect();
		}
		return responseBody;
	}
}
